/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package pacoteframe;

import com.sun.glass.events.KeyEvent;
import java.awt.*;
import java.io.IOException;
//import java.awt.event.ContainerListener;
//import java.awt.event.ItemListener;
import java.sql.*;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.InputMismatchException;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.stage.Screen;
import javax.swing.*;
//import javax.swing.JOptionPane;
//import javax.swing.JTable;
//import javax.swing.JTextField;
import javax.swing.table.*;
import javax.swing.text.MaskFormatter;
import pacoteconexao.ConexaoMySQL;
import pacoteclasse.Cliente;
import pacotevalidacao.ValidaCNPJ;
import pacotevalidacao.ValidaCPF;
/**
 *
 * @author Izak
 * @author Bruno
 */

public class FrmCadCliente extends javax.swing.JFrame {
    Cliente cnnCliente = new Cliente();
    String modo="pesquisa",backupFantasia="",backupIE="";
    int[] listCidade;
    ResultSet rsPesquisa=null;
    /**
     * Creates new form form_inserecliente
     */
    public FrmCadCliente() {
        initComponents();
        setLocationRelativeTo(null);
//        int x=Toolkit.getDefaultToolkit().getScreenSize().width;
//        int y=Toolkit.getDefaultToolkit().getScreenSize().height;
//        setBounds(x/2-800/2, y/2-580/2, 800, 580); // alinha no centro da tela
        cnnCliente.conectar(); // aqui eh feita a conexão e usada enquanto o form está aberto
        pesquisar();
        listCidade = new int[100];
        preencherCmbCidade();
        pangCliente.setEnabledAt(1, false);
        botEditar_cliente.setEnabled(false);
        botExcluir_cliente.setEnabled(false);
        txtId_cliente.setEnabled(false);
        lblFantasia.setEnabled(false);
        txtFantasia_cliente.setEnabled(false);
        lblIE.setEnabled(false);
        txtIe_cliente.setEnabled(false);
        txtPesquisa_cliente.requestFocus();
        lblInvalido.setVisible(false);
        botNovoPedido.setEnabled(false);
        botVerPedidos.setEnabled(false);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        grpbTipo_cliente = new javax.swing.ButtonGroup();
        entityManager = java.beans.Beans.isDesignTime() ? null : javax.persistence.Persistence.createEntityManagerFactory("db_plastek?zeroDateTimeBehavior=convertToNullPU").createEntityManager();
        tbClienteQuery = java.beans.Beans.isDesignTime() ? null : entityManager.createQuery("SELECT t FROM TbCliente t");
        tbClienteList = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : tbClienteQuery.getResultList();
        tbClienteQuery1 = java.beans.Beans.isDesignTime() ? null : entityManager.createQuery("SELECT t FROM TbCliente t");
        tbClienteList1 = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : tbClienteQuery1.getResultList();
        pangCliente = new javax.swing.JTabbedPane();
        panPesquisa = new javax.swing.JPanel();
        txtPesquisa_cliente = new javax.swing.JTextField();
        botPesquisar = new javax.swing.JButton();
        botNovo_cliente = new javax.swing.JButton();
        botEditar_cliente = new javax.swing.JButton();
        botExcluir_cliente = new javax.swing.JButton();
        botNovoPedido = new javax.swing.JButton();
        botVerPedidos = new javax.swing.JButton();
        panTabela = new javax.swing.JScrollPane();
        tblCliente = new javax.swing.JTable();
        panCadastro = new javax.swing.JPanel();
        botSalvar = new javax.swing.JButton();
        botLimpar = new javax.swing.JButton();
        botCancelar = new javax.swing.JButton();
        lblId_cliente = new javax.swing.JLabel();
        txtId_cliente = new javax.swing.JTextField();
        lblNome = new javax.swing.JLabel();
        txtNome_cliente = new javax.swing.JTextField();
        lblTipo = new javax.swing.JLabel();
        bradPessoaFisica = new javax.swing.JRadioButton();
        bradPessoaJuridica = new javax.swing.JRadioButton();
        lblFantasia = new javax.swing.JLabel();
        txtFantasia_cliente = new javax.swing.JTextField();
        lblTelefone = new javax.swing.JLabel();
        lblTelefone2 = new javax.swing.JLabel();
        lblCnpj = new javax.swing.JLabel();
        lblIE = new javax.swing.JLabel();
        lblEmail = new javax.swing.JLabel();
        txtEmail_cliente = new javax.swing.JTextField();
        lblCidade = new javax.swing.JLabel();
        cmbCidade_cliente = new javax.swing.JComboBox();
        lblEndereco = new javax.swing.JLabel();
        txtEndereco_cliente = new javax.swing.JTextField();
        lblBairro = new javax.swing.JLabel();
        txtBairro_cliente = new javax.swing.JTextField();
        lblCEP = new javax.swing.JLabel();
        lblObs = new javax.swing.JLabel();
        panObs = new javax.swing.JScrollPane();
        txtObs_cliente = new javax.swing.JTextArea();
        txtTel2_cliente = new javax.swing.JFormattedTextField();
        txtTel1_cliente = new javax.swing.JFormattedTextField();
        txtCep_cliente = new javax.swing.JFormattedTextField();
        txtIe_cliente = new javax.swing.JFormattedTextField();
        txtCnpj_cliente = new javax.swing.JFormattedTextField();
        lblInvalido = new javax.swing.JLabel();

        setTitle("Cadastrar Clientes");
        setLocationByPlatform(true);
        setName("frmCadCliente"); // NOI18N
        setResizable(false);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosed(java.awt.event.WindowEvent evt) {
                formWindowClosed(evt);
            }
            public void windowOpened(java.awt.event.WindowEvent evt) {
                formWindowOpened(evt);
            }
        });

        pangCliente.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        pangCliente.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                pangClienteFocusGained(evt);
            }
        });

        txtPesquisa_cliente.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        txtPesquisa_cliente.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtPesquisa_clienteActionPerformed(evt);
            }
        });
        txtPesquisa_cliente.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                txtPesquisa_clienteFocusGained(evt);
            }
        });
        txtPesquisa_cliente.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                txtPesquisa_clienteKeyReleased(evt);
            }
        });

        botPesquisar.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        botPesquisar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/pacoteicones/Pesquisar.png"))); // NOI18N
        botPesquisar.setText("Pesquisar");
        botPesquisar.setFocusTraversalPolicyProvider(true);
        botPesquisar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                botPesquisarActionPerformed(evt);
            }
        });

        botNovo_cliente.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        botNovo_cliente.setIcon(new javax.swing.ImageIcon(getClass().getResource("/pacoteicones/Novo.png"))); // NOI18N
        botNovo_cliente.setText("Novo");
        botNovo_cliente.setToolTipText("");
        botNovo_cliente.setIconTextGap(15);
        botNovo_cliente.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                botNovo_clienteActionPerformed(evt);
            }
        });

        botEditar_cliente.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        botEditar_cliente.setIcon(new javax.swing.ImageIcon(getClass().getResource("/pacoteicones/Editar.png"))); // NOI18N
        botEditar_cliente.setText("Editar");
        botEditar_cliente.setToolTipText("");
        botEditar_cliente.setIconTextGap(15);
        botEditar_cliente.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                botEditar_clienteActionPerformed(evt);
            }
        });

        botExcluir_cliente.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        botExcluir_cliente.setIcon(new javax.swing.ImageIcon(getClass().getResource("/pacoteicones/Excluir.png"))); // NOI18N
        botExcluir_cliente.setText("Excluir");
        botExcluir_cliente.setToolTipText("");
        botExcluir_cliente.setIconTextGap(15);
        botExcluir_cliente.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                botExcluir_clienteActionPerformed(evt);
            }
        });

        botNovoPedido.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        botNovoPedido.setIcon(new javax.swing.ImageIcon(getClass().getResource("/pacoteicones/Pedidos.png"))); // NOI18N
        botNovoPedido.setText("Novo Pedido");
        botNovoPedido.setToolTipText("");
        botNovoPedido.setIconTextGap(10);

        botVerPedidos.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        botVerPedidos.setIcon(new javax.swing.ImageIcon(getClass().getResource("/pacoteicones/Pedidos_2.png"))); // NOI18N
        botVerPedidos.setText("Ver Pedidos");
        botVerPedidos.setToolTipText("");
        botVerPedidos.setIconTextGap(15);
        botVerPedidos.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                botVerPedidosActionPerformed(evt);
            }
        });

        tblCliente.setAutoCreateRowSorter(true);
        tblCliente.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {

            }
        ));
        tblCliente.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        tblCliente.addComponentListener(new java.awt.event.ComponentAdapter() {
            public void componentShown(java.awt.event.ComponentEvent evt) {
                tblClienteComponentShown(evt);
            }
        });
        tblCliente.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                tblClienteFocusGained(evt);
            }
            public void focusLost(java.awt.event.FocusEvent evt) {
                tblClienteFocusLost(evt);
            }
        });
        panTabela.setViewportView(tblCliente);
        tblCliente.getColumnModel().getSelectionModel().setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        tblCliente.getAccessibleContext().setAccessibleName("");

        javax.swing.GroupLayout panPesquisaLayout = new javax.swing.GroupLayout(panPesquisa);
        panPesquisa.setLayout(panPesquisaLayout);
        panPesquisaLayout.setHorizontalGroup(
            panPesquisaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(panPesquisaLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(panPesquisaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panPesquisaLayout.createSequentialGroup()
                        .addComponent(txtPesquisa_cliente)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(botPesquisar, javax.swing.GroupLayout.PREFERRED_SIZE, 123, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(panTabela, javax.swing.GroupLayout.PREFERRED_SIZE, 601, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(panPesquisaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(botNovo_cliente, javax.swing.GroupLayout.DEFAULT_SIZE, 154, Short.MAX_VALUE)
                    .addComponent(botEditar_cliente, javax.swing.GroupLayout.DEFAULT_SIZE, 154, Short.MAX_VALUE)
                    .addComponent(botExcluir_cliente, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(botVerPedidos, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(botNovoPedido, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap(16, Short.MAX_VALUE))
        );
        panPesquisaLayout.setVerticalGroup(
            panPesquisaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(panPesquisaLayout.createSequentialGroup()
                .addGap(17, 17, 17)
                .addGroup(panPesquisaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtPesquisa_cliente, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(botPesquisar, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(panPesquisaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(panPesquisaLayout.createSequentialGroup()
                        .addComponent(botNovo_cliente, javax.swing.GroupLayout.PREFERRED_SIZE, 57, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(botEditar_cliente, javax.swing.GroupLayout.PREFERRED_SIZE, 57, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(botExcluir_cliente, javax.swing.GroupLayout.PREFERRED_SIZE, 57, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(109, 109, 109)
                        .addComponent(botNovoPedido, javax.swing.GroupLayout.PREFERRED_SIZE, 57, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 55, Short.MAX_VALUE)
                        .addComponent(botVerPedidos, javax.swing.GroupLayout.PREFERRED_SIZE, 57, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(panTabela, javax.swing.GroupLayout.DEFAULT_SIZE, 471, Short.MAX_VALUE))
                .addContainerGap())
        );

        pangCliente.addTab("Clientes", panPesquisa);

        botSalvar.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        botSalvar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/pacoteicones/Salvar.png"))); // NOI18N
        botSalvar.setText("Salvar");
        botSalvar.setIconTextGap(10);
        botSalvar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                botSalvarActionPerformed(evt);
            }
        });

        botLimpar.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        botLimpar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/pacoteicones/Limpar.png"))); // NOI18N
        botLimpar.setText("Limpar");
        botLimpar.setIconTextGap(10);
        botLimpar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                botLimparActionPerformed(evt);
            }
        });

        botCancelar.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        botCancelar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/pacoteicones/Cancelar.png"))); // NOI18N
        botCancelar.setText("Cancelar");
        botCancelar.setIconTextGap(5);
        botCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                botCancelarActionPerformed(evt);
            }
        });

        lblId_cliente.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        lblId_cliente.setText("Código:");

        txtId_cliente.setEditable(false);
        txtId_cliente.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N

        lblNome.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        lblNome.setText("Nome:");

        txtNome_cliente.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        txtNome_cliente.setFocusTraversalPolicyProvider(true);
        txtNome_cliente.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                txtNome_clienteFocusLost(evt);
            }
        });
        txtNome_cliente.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                txtNome_clienteKeyTyped(evt);
            }
        });

        lblTipo.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        lblTipo.setText("Tipo:");

        grpbTipo_cliente.add(bradPessoaFisica);
        bradPessoaFisica.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        bradPessoaFisica.setSelected(true);
        bradPessoaFisica.setText("Pessoa Física");
        bradPessoaFisica.addChangeListener(new javax.swing.event.ChangeListener() {
            public void stateChanged(javax.swing.event.ChangeEvent evt) {
                bradPessoaFisicaStateChanged(evt);
            }
        });
        bradPessoaFisica.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                bradPessoaFisicaItemStateChanged(evt);
            }
        });
        bradPessoaFisica.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bradPessoaFisicaActionPerformed(evt);
            }
        });
        bradPessoaFisica.addInputMethodListener(new java.awt.event.InputMethodListener() {
            public void caretPositionChanged(java.awt.event.InputMethodEvent evt) {
                bradPessoaFisicaCaretPositionChanged(evt);
            }
            public void inputMethodTextChanged(java.awt.event.InputMethodEvent evt) {
            }
        });
        bradPessoaFisica.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
            public void propertyChange(java.beans.PropertyChangeEvent evt) {
                bradPessoaFisicaPropertyChange(evt);
            }
        });

        grpbTipo_cliente.add(bradPessoaJuridica);
        bradPessoaJuridica.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        bradPessoaJuridica.setText("Pessoa Jurídica");
        bradPessoaJuridica.addChangeListener(new javax.swing.event.ChangeListener() {
            public void stateChanged(javax.swing.event.ChangeEvent evt) {
                bradPessoaJuridicaStateChanged(evt);
            }
        });
        bradPessoaJuridica.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                bradPessoaJuridicaItemStateChanged(evt);
            }
        });
        bradPessoaJuridica.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bradPessoaJuridicaActionPerformed(evt);
            }
        });
        bradPessoaJuridica.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
            public void propertyChange(java.beans.PropertyChangeEvent evt) {
                bradPessoaJuridicaPropertyChange(evt);
            }
        });

        lblFantasia.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        lblFantasia.setText("Nome Fantasia:");

        txtFantasia_cliente.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N

        lblTelefone.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        lblTelefone.setText("Telefone 1:");

        lblTelefone2.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        lblTelefone2.setText("Telefone 2:");

        lblCnpj.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        lblCnpj.setText("CPF:");

        lblIE.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        lblIE.setText("IE:");

        lblEmail.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        lblEmail.setText("E-mail:");

        txtEmail_cliente.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N

        lblCidade.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        lblCidade.setText("Cidade:");

        cmbCidade_cliente.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Selecione..." }));

        lblEndereco.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        lblEndereco.setText("Endereço:");

        txtEndereco_cliente.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N

        lblBairro.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        lblBairro.setText("Bairro:");

        txtBairro_cliente.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N

        lblCEP.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        lblCEP.setText("CEP:");

        lblObs.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        lblObs.setText("Obs.:");

        txtObs_cliente.setColumns(20);
        txtObs_cliente.setRows(1);
        panObs.setViewportView(txtObs_cliente);

        try {
            txtTel2_cliente.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("(##) ####-####*")));
        } catch (java.text.ParseException ex) {
            ex.printStackTrace();
        }
        txtTel2_cliente.setToolTipText("");
        txtTel2_cliente.setFocusLostBehavior(javax.swing.JFormattedTextField.PERSIST);
        txtTel2_cliente.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N

        try {
            txtTel1_cliente.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("(##) ####-####*")));
        } catch (java.text.ParseException ex) {
            ex.printStackTrace();
        }
        txtTel1_cliente.setToolTipText("");
        txtTel1_cliente.setFocusLostBehavior(javax.swing.JFormattedTextField.PERSIST);
        txtTel1_cliente.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        txtTel1_cliente.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                txtTel1_clienteFocusLost(evt);
            }
        });

        try {
            txtCep_cliente.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("#####-###")));
        } catch (java.text.ParseException ex) {
            ex.printStackTrace();
        }
        txtCep_cliente.setFocusLostBehavior(javax.swing.JFormattedTextField.PERSIST);
        txtCep_cliente.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        txtCep_cliente.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtCep_clienteActionPerformed(evt);
            }
        });

        try {
            txtIe_cliente.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("###.###.###.###")));
        } catch (java.text.ParseException ex) {
            ex.printStackTrace();
        }
        txtIe_cliente.setFocusLostBehavior(javax.swing.JFormattedTextField.PERSIST);
        txtIe_cliente.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N

        try {
            txtCnpj_cliente.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("###.###.###-##")));
        } catch (java.text.ParseException ex) {
            ex.printStackTrace();
        }
        txtCnpj_cliente.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        txtCnpj_cliente.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtCnpj_clienteActionPerformed(evt);
            }
        });
        txtCnpj_cliente.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                txtCnpj_clienteFocusLost(evt);
            }
        });
        txtCnpj_cliente.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                txtCnpj_clienteKeyTyped(evt);
            }
        });

        lblInvalido.setForeground(new java.awt.Color(255, 0, 0));
        lblInvalido.setText("* CPF/CNPJ inválidos");

        javax.swing.GroupLayout panCadastroLayout = new javax.swing.GroupLayout(panCadastro);
        panCadastro.setLayout(panCadastroLayout);
        panCadastroLayout.setHorizontalGroup(
            panCadastroLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panCadastroLayout.createSequentialGroup()
                .addGap(15, 15, 15)
                .addGroup(panCadastroLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(panCadastroLayout.createSequentialGroup()
                        .addGroup(panCadastroLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(lblTelefone, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(lblFantasia, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(lblNome, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(lblId_cliente, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(lblCnpj, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(panCadastroLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(txtFantasia_cliente, javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(txtNome_cliente)
                            .addGroup(panCadastroLayout.createSequentialGroup()
                                .addComponent(txtId_cliente)
                                .addGap(36, 36, 36)
                                .addComponent(lblTipo)
                                .addGap(28, 28, 28)
                                .addComponent(bradPessoaFisica)
                                .addGap(46, 46, 46)
                                .addComponent(bradPessoaJuridica))
                            .addGroup(javax.swing.GroupLayout.Alignment.LEADING, panCadastroLayout.createSequentialGroup()
                                .addGroup(panCadastroLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addGroup(panCadastroLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                        .addComponent(txtCnpj_cliente)
                                        .addComponent(txtTel1_cliente, javax.swing.GroupLayout.DEFAULT_SIZE, 209, Short.MAX_VALUE))
                                    .addComponent(lblInvalido, javax.swing.GroupLayout.PREFERRED_SIZE, 181, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addGap(18, 18, 18)
                                .addGroup(panCadastroLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addGroup(panCadastroLayout.createSequentialGroup()
                                        .addComponent(lblIE, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addComponent(txtIe_cliente))
                                    .addGroup(panCadastroLayout.createSequentialGroup()
                                        .addComponent(lblTelefone2)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                        .addComponent(txtTel2_cliente))))))
                    .addGroup(panCadastroLayout.createSequentialGroup()
                        .addGroup(panCadastroLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(panCadastroLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                .addComponent(lblBairro, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(lblEndereco, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(lblCidade, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(lblEmail, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                            .addComponent(lblObs, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 94, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(panCadastroLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(txtEmail_cliente)
                            .addComponent(cmbCidade_cliente, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(txtEndereco_cliente)
                            .addGroup(panCadastroLayout.createSequentialGroup()
                                .addComponent(txtBairro_cliente, javax.swing.GroupLayout.PREFERRED_SIZE, 324, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(18, 18, 18)
                                .addComponent(lblCEP, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(txtCep_cliente, javax.swing.GroupLayout.DEFAULT_SIZE, 129, Short.MAX_VALUE))
                            .addComponent(panObs))))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(panCadastroLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(panCadastroLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                        .addComponent(botSalvar, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(botLimpar, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 137, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(botCancelar))
                .addContainerGap())
        );
        panCadastroLayout.setVerticalGroup(
            panCadastroLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(panCadastroLayout.createSequentialGroup()
                .addGap(35, 35, 35)
                .addGroup(panCadastroLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(botSalvar)
                    .addGroup(panCadastroLayout.createSequentialGroup()
                        .addGroup(panCadastroLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(txtId_cliente, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(lblId_cliente, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(lblTipo, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(bradPessoaFisica)
                            .addComponent(bradPessoaJuridica))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(panCadastroLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(lblNome, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(txtNome_cliente, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(panCadastroLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(lblFantasia, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(txtFantasia_cliente, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(panCadastroLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(lblTelefone, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(txtTel2_cliente, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(lblTelefone2)
                            .addComponent(txtTel1_cliente, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addGroup(panCadastroLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                    .addGroup(panCadastroLayout.createSequentialGroup()
                        .addGap(10, 10, 10)
                        .addGroup(panCadastroLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(lblIE, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(lblCnpj, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(txtIe_cliente, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(txtCnpj_cliente, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(lblInvalido)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(panCadastroLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(txtEmail_cliente, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(lblEmail))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(panCadastroLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(cmbCidade_cliente, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(lblCidade, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(panCadastroLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(txtEndereco_cliente, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(lblEndereco, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(panCadastroLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(txtBairro_cliente, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(lblBairro, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(lblCEP, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(txtCep_cliente, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(panCadastroLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(panObs, javax.swing.GroupLayout.PREFERRED_SIZE, 59, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(lblObs, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addGroup(panCadastroLayout.createSequentialGroup()
                        .addGap(47, 47, 47)
                        .addComponent(botLimpar, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(botCancelar)))
                .addGap(114, 114, 114))
        );

        pangCliente.addTab("Cadastrar", panCadastro);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(pangCliente))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(pangCliente, javax.swing.GroupLayout.PREFERRED_SIZE, 529, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        getAccessibleContext().setAccessibleDescription("");

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private ResultSet atualizarTabela(String sql){
        ResultSet rsCliente = null;
        final DefaultTableModel modelo = new DefaultTableModel(){
            @Override
            public boolean isCellEditable(int row, int column){
                return false;
            }
        };
        try {
            modelo.addColumn("Código");
            modelo.addColumn("Nome");
            modelo.addColumn("Telefone");
            modelo.addColumn("CNPJ / CPF");
            modelo.addColumn("E-mail");
            modelo.addColumn("Endereço");
            
            rsCliente=cnnCliente.consultar(sql);
        
            while(rsCliente.next()){
                modelo.addRow(new Object[]{
                    rsCliente.getInt("id_cliente"),
                    rsCliente.getString("nome_cliente"),
                    rsCliente.getString("tel1_cliente"),
                    rsCliente.getString("cnpj_cliente"),
                    rsCliente.getString("email_cliente"),
                    rsCliente.getString("endereco_cliente")
                });
            }
            tblCliente.setModel(modelo);
            tblCliente.setSelectionMode(0);
            rsCliente.beforeFirst(); // volta para o inicio
        } catch (Exception e) {
            JOptionPane.showMessageDialog(null,"Erro na inicialização: " + e);
        }
        return rsCliente;
    }
    
    
    private void pesquisar(){
        try{
            txtPesquisa_cliente.requestFocus();
            String pesquisa = "\"%"+txtPesquisa_cliente.getText()+"%\"";
            rsPesquisa = atualizarTabela("SELECT * FROM tb_cliente WHERE "+
                "id_cliente like "+pesquisa+
                " OR nome_cliente like "+pesquisa+
                " OR fantasia_cliente like "+pesquisa+
                " OR tel1_cliente like "+pesquisa+
                " OR tel2_cliente like "+pesquisa+
                " OR tipo_cliente like "+pesquisa+
                " OR cnpj_cliente like "+pesquisa+
                " OR ie_cliente like "+pesquisa+
                " OR email_cliente like "+pesquisa+
                " OR endereco_cliente like "+pesquisa+
                " OR bairro_cliente like "+pesquisa+
                ";");
        }
        catch(Exception e){
            JOptionPane.showMessageDialog(null,"Erro ao pesquisar: " + e);
        }
    }
    
    private void preencherCmbCidade(){
        ResultSet rsCidade;
        rsCidade = cnnCliente.consultar("SELECT * FROM tb_cidade");
        int i=0;
        try {
            while(rsCidade.next()){
                listCidade[++i]=(rsCidade.getInt("id_cidade"));
                cmbCidade_cliente.addItem(rsCidade.getString("id_cidade")+" - "+rsCidade.getString("nome_cidade"));
            }
        } catch (SQLException ex) {
            JOptionPane.showMessageDialog(null,"Erro enaquanto carregava as cidades: " + ex);
            Logger.getLogger(FrmCadCliente.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    
    private void formWindowOpened(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowOpened
        
    }//GEN-LAST:event_formWindowOpened

    private void botNovo_clienteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botNovo_clienteActionPerformed

        limparCampos();
        pangCliente.setSelectedIndex(0);
        pangCliente.setEnabledAt(1, false);
        pangCliente.setEnabledAt(1, true);
        pangCliente.setSelectedIndex(1);
        bradPessoaFisica.setSelected(true);
        modo="novo";
        mudarParaCPF();
    }//GEN-LAST:event_botNovo_clienteActionPerformed

    private void botEditar_clienteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botEditar_clienteActionPerformed

        modo="editar";
        int i,idCidade;
        try{
            for(i=0;i<=tblCliente.getSelectedRow();i++){
                rsPesquisa.next(); // acha o registro que o usuário clicou
            }
            pangCliente.setEnabledAt(1, true);
            pangCliente.setSelectedIndex(1);
            if(rsPesquisa.getString("tipo_cliente").equals("Pessoa Física")){
                bradPessoaFisica.setSelected(true);
                mudarParaCPF();
            }else if(rsPesquisa.getString("tipo_cliente").equals("Pessoa Jurídica")){
                bradPessoaJuridica.setSelected(true);
                mudarParaCNPJ();
            }
            txtId_cliente.setText(rsPesquisa.getString("id_cliente"));
            txtNome_cliente.setText(rsPesquisa.getString("nome_cliente"));
            txtFantasia_cliente.setText(rsPesquisa.getString("fantasia_cliente"));
            txtTel1_cliente.setText(rsPesquisa.getString("tel1_cliente"));
            txtTel2_cliente.setText(rsPesquisa.getString("tel2_cliente"));
            
            txtCnpj_cliente.setValue(rsPesquisa.getString("cnpj_cliente"));
            txtIe_cliente.setText(rsPesquisa.getString("ie_cliente"));
            txtEmail_cliente.setText(rsPesquisa.getString("email_cliente"));
            idCidade=rsPesquisa.getInt("cidade_cliente");
            i=0;
            while(listCidade[i]!=idCidade)
                i++;
            cmbCidade_cliente.setSelectedIndex(i);
            txtEndereco_cliente.setText(rsPesquisa.getString("endereco_cliente"));
            txtBairro_cliente.setText(rsPesquisa.getString("bairro_cliente"));
            txtCep_cliente.setText(rsPesquisa.getString("cep_cliente"));
            txtObs_cliente.setText(rsPesquisa.getString("obs_cliente"));
            txtNome_cliente.requestFocus();
        }catch(SQLException ex){
            JOptionPane.showMessageDialog(null,"Erro na edição: " + ex);
            Logger.getLogger(FrmCadCliente.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_botEditar_clienteActionPerformed

    private void botExcluir_clienteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botExcluir_clienteActionPerformed
        if(JOptionPane.showConfirmDialog(pangCliente, 
        "Deseja realmente excluir este cliente?","Confirmação",
        JOptionPane.YES_NO_OPTION)==JOptionPane.YES_OPTION){
            cnnCliente.conectar();
            ResultSet listCliente;
            int i;
            try{
                listCliente=cnnCliente.consultar("SELECT * FROM tb_cliente;");
                for(i=0;i<=tblCliente.getSelectedRow();i++){
                    listCliente.next();
                }
                cnnCliente.excluirCliente(listCliente.getString("id_cliente"));
                pesquisar();
                JOptionPane.showMessageDialog(null,"Cliente excluído com sucesso!");
            }catch(Exception e){
                JOptionPane.showMessageDialog(null,"Erro na exclusão: " + e);
            }
        }
    }//GEN-LAST:event_botExcluir_clienteActionPerformed

    
    private void botPesquisarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botPesquisarActionPerformed
        pesquisar();
    }//GEN-LAST:event_botPesquisarActionPerformed

    private void formWindowClosed(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosed
        cnnCliente.desconectar();
    }//GEN-LAST:event_formWindowClosed

    private void txtPesquisa_clienteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtPesquisa_clienteActionPerformed
        pesquisar();
    }//GEN-LAST:event_txtPesquisa_clienteActionPerformed

    private void txtPesquisa_clienteKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtPesquisa_clienteKeyReleased
        pesquisar();
    }//GEN-LAST:event_txtPesquisa_clienteKeyReleased

    private void tblClienteComponentShown(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_tblClienteComponentShown

    }//GEN-LAST:event_tblClienteComponentShown

    private void tblClienteFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_tblClienteFocusGained
        if(modo.equals("pesquisa")){
            botNovo_cliente.setEnabled(true);
            botEditar_cliente.setEnabled(true);
            botExcluir_cliente.setEnabled(true);
            botNovoPedido.setEnabled(true);
            botVerPedidos.setEnabled(true);
        }
    }//GEN-LAST:event_tblClienteFocusGained

    private void tblClienteFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_tblClienteFocusLost
        
    }//GEN-LAST:event_tblClienteFocusLost

    private void txtPesquisa_clienteFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_txtPesquisa_clienteFocusGained
        botEditar_cliente.setEnabled(false);
        botExcluir_cliente.setEnabled(false);
        botNovoPedido.setEnabled(false);
        botVerPedidos.setEnabled(false);
        if(!modo.equals("pesquisa")){
            botNovo_cliente.setEnabled(false);
        }
    }//GEN-LAST:event_txtPesquisa_clienteFocusGained

    private void botCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botCancelarActionPerformed
        String msg="";
        if(modo.equals("novo"))
            msg="Deseja realmente cancelar o novo cadastro?";
        else if(modo.equals("editar"))
            msg="Deseja realmente cancelar a edição?";

        if(JOptionPane.showConfirmDialog(pangCliente,
            msg,"Confirmação",
            JOptionPane.YES_NO_OPTION)==JOptionPane.YES_OPTION){
            pangCliente.setSelectedIndex(0);
            pangCliente.setEnabledAt(1, false);
            modo="pesquisa";
            botNovo_cliente.setEnabled(true);
            pesquisar();
        }
    }//GEN-LAST:event_botCancelarActionPerformed

    private void limparCampos(){
        txtId_cliente.setText("");
        txtNome_cliente.setText("");
        txtFantasia_cliente.setText("");
        txtTel1_cliente.setText("");
        txtTel1_cliente.setValue(null);
        txtTel2_cliente.setText("");
        txtTel2_cliente.setValue(null);
        txtCnpj_cliente.setText("");
        txtCnpj_cliente.setValue(false);
        txtIe_cliente.setText("");
        txtIe_cliente.setValue(null);
        txtEmail_cliente.setText("");
        cmbCidade_cliente.setSelectedIndex(0);
        txtEndereco_cliente.setText("");
        txtBairro_cliente.setText("");
        txtCep_cliente.setText("");
        txtObs_cliente.setText("");
    }
    private void botLimparActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botLimparActionPerformed
        if(JOptionPane.showConfirmDialog(pangCliente,
            "Deseja realmente limpar todos os dados da tela?","Confirmação",
            JOptionPane.YES_NO_OPTION)==JOptionPane.YES_OPTION){
        limparCampos();
        }
    }//GEN-LAST:event_botLimparActionPerformed

    private void botSalvarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botSalvarActionPerformed
        String strTipo;
        int idCidade,i;
        Cliente cnnCliente = new Cliente();
        try{
            if(txtNome_cliente.getText().equals("")){
                JOptionPane.showMessageDialog(null,"Informe o nome do cliente!");
                txtNome_cliente.requestFocus();
                return;
            }

            if(cmbCidade_cliente.getSelectedIndex()==0){
                JOptionPane.showMessageDialog(null,"Informe a cidade do cliente!");
                cmbCidade_cliente.requestFocus();
                return;
            }
            if(bradPessoaFisica.isSelected()){
                strTipo="Pessoa Física";
                if(!ValidaCPF.isCPF(txtCnpj_cliente.getText())){
                    JOptionPane.showMessageDialog(null,"O CPF é inválido!");
                    txtCnpj_cliente.requestFocus();
                    return;
                }
            }else{
                strTipo="Pessoa Jurídica";
                if(!ValidaCNPJ.isCNPJ(txtCnpj_cliente.getText())){
                    JOptionPane.showMessageDialog(null,"O CNPJ é inválido!");
                    txtCnpj_cliente.requestFocus();
                    return;
                }
            }
            
            if(JOptionPane.showConfirmDialog(pangCliente,
                "Deseja realmente salvar os dados?","Confirmação",
                JOptionPane.YES_NO_OPTION)==JOptionPane.YES_OPTION){

            
            idCidade=listCidade[cmbCidade_cliente.getSelectedIndex()]; // acha o id da cidade
            cnnCliente.conectar();
            if(modo.equals("novo")){
                cnnCliente.inserirCliente(
                    txtNome_cliente.getText(),
                    txtFantasia_cliente.getText(),
                    txtTel1_cliente.getText(),
                    txtTel2_cliente.getText(),
                    strTipo,
                    txtCnpj_cliente.getText(),
                    txtIe_cliente.getText(),
                    txtEmail_cliente.getText(),
                    idCidade,
                    txtEndereco_cliente.getText(),
                    txtBairro_cliente.getText(),
                    txtCep_cliente.getText(),
                    txtObs_cliente.getText()
                );
            }else if (modo.equals("editar")){
                cnnCliente.editarCliente(
                    txtId_cliente.getText(),
                    txtNome_cliente.getText(),
                    txtFantasia_cliente.getText(),
                    txtTel1_cliente.getText(),
                    txtTel2_cliente.getText(),
                    strTipo,
                    txtCnpj_cliente.getText(),
                    txtIe_cliente.getText(),
                    txtEmail_cliente.getText(),
                    idCidade,
                    txtEndereco_cliente.getText(),
                    txtBairro_cliente.getText(),
                    txtCep_cliente.getText(),
                    txtObs_cliente.getText()
                );
            }
            JOptionPane.showMessageDialog(null,"Dados salvos com sucesso!");
            pangCliente.setSelectedIndex(0);
            pangCliente.setEnabledAt(1, false);
            limparCampos();
            modo="pesquisa";
            botNovo_cliente.setEnabled(true);

            pesquisar();
        }
        }catch(Exception e){
            JOptionPane.showMessageDialog(null,"Erro na inserção: " + e);
        }
    }//GEN-LAST:event_botSalvarActionPerformed
    private void mudarParaCNPJ(){
        try {
            lblCnpj.setText("CNPJ:");
            txtCnpj_cliente.setValue(null);
            txtCnpj_cliente.setFormatterFactory(
                new javax.swing.text.DefaultFormatterFactory(
                    new javax.swing.text.MaskFormatter("##.###.###/####-##")));
            txtFantasia_cliente.setText(backupFantasia);
            lblFantasia.setEnabled(true);
            txtFantasia_cliente.setEnabled(true);
            lblIE.setEnabled(true);
            txtIe_cliente.setEnabled(true);
            txtIe_cliente.setText(backupIE);
            lblInvalido.setVisible(false);
            txtNome_cliente.requestFocus();
        } catch (ParseException ex) {
            Logger.getLogger(FrmCadCliente.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    
    private void mudarParaCPF(){
        try {
            lblCnpj.setText("CPF:");
            txtCnpj_cliente.setValue(null);
            txtCnpj_cliente.setFormatterFactory(
                new javax.swing.text.DefaultFormatterFactory(
                    new javax.swing.text.MaskFormatter("###.###.###-##")));
            backupFantasia=txtFantasia_cliente.getText();
            lblFantasia.setEnabled(false);
            txtFantasia_cliente.setEnabled(false);
            txtFantasia_cliente.setText("");
            backupIE=txtIe_cliente.getText();
            lblIE.setEnabled(false);
            txtIe_cliente.setEnabled(false);
            txtIe_cliente.setText("");
            txtIe_cliente.setValue(null);
            lblInvalido.setVisible(false);
            txtNome_cliente.requestFocus();
        } catch (ParseException ex) {
            Logger.getLogger(FrmCadCliente.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    
    private void bradPessoaJuridicaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bradPessoaJuridicaActionPerformed
        if(bradPessoaJuridica.isSelected()){
            mudarParaCNPJ();
        }
    }//GEN-LAST:event_bradPessoaJuridicaActionPerformed

    private void bradPessoaFisicaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bradPessoaFisicaActionPerformed
        if(bradPessoaFisica.isSelected()){
            mudarParaCPF();
        }
    }//GEN-LAST:event_bradPessoaFisicaActionPerformed

    private void txtCep_clienteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtCep_clienteActionPerformed
        
    }//GEN-LAST:event_txtCep_clienteActionPerformed

    private void txtCnpj_clienteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtCnpj_clienteActionPerformed
        
    }//GEN-LAST:event_txtCnpj_clienteActionPerformed

    private void botVerPedidosActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botVerPedidosActionPerformed

    }//GEN-LAST:event_botVerPedidosActionPerformed

    private void txtNome_clienteKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtNome_clienteKeyTyped

    }//GEN-LAST:event_txtNome_clienteKeyTyped

    private void txtNome_clienteFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_txtNome_clienteFocusLost
        
    }//GEN-LAST:event_txtNome_clienteFocusLost

    private void txtCnpj_clienteKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtCnpj_clienteKeyTyped

    }//GEN-LAST:event_txtCnpj_clienteKeyTyped

    private void bradPessoaFisicaStateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_bradPessoaFisicaStateChanged
        
    }//GEN-LAST:event_bradPessoaFisicaStateChanged

    private void bradPessoaJuridicaStateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_bradPessoaJuridicaStateChanged
        
    }//GEN-LAST:event_bradPessoaJuridicaStateChanged

    private void bradPessoaFisicaPropertyChange(java.beans.PropertyChangeEvent evt) {//GEN-FIRST:event_bradPessoaFisicaPropertyChange
        
    }//GEN-LAST:event_bradPessoaFisicaPropertyChange

    private void bradPessoaJuridicaPropertyChange(java.beans.PropertyChangeEvent evt) {//GEN-FIRST:event_bradPessoaJuridicaPropertyChange
        
    }//GEN-LAST:event_bradPessoaJuridicaPropertyChange

    private void bradPessoaFisicaItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_bradPessoaFisicaItemStateChanged
        
    }//GEN-LAST:event_bradPessoaFisicaItemStateChanged

    private void bradPessoaFisicaCaretPositionChanged(java.awt.event.InputMethodEvent evt) {//GEN-FIRST:event_bradPessoaFisicaCaretPositionChanged
        
    }//GEN-LAST:event_bradPessoaFisicaCaretPositionChanged

    private void bradPessoaJuridicaItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_bradPessoaJuridicaItemStateChanged
        
    }//GEN-LAST:event_bradPessoaJuridicaItemStateChanged

    private void txtCnpj_clienteFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_txtCnpj_clienteFocusLost
        CharSequence c = "123456789";
        if(!(txtCnpj_cliente.getText().equals("   .   .   -  ")||
            txtCnpj_cliente.getText().equals("  .   .   /    -  "))){
            if(bradPessoaFisica.isSelected()){
                if(!ValidaCPF.isCPF(txtCnpj_cliente.getText())){
                    txtCnpj_cliente.setValue(null);
                    lblInvalido.setText("* CPF inválido!");
                    lblInvalido.setVisible(true);
                }else{
                    lblInvalido.setVisible(false);
                }
            }else if(bradPessoaJuridica.isSelected()){
                if(!ValidaCNPJ.isCNPJ(txtCnpj_cliente.getText())){
                    txtCnpj_cliente.setValue(null);
                    lblInvalido.setText("* CNPJ inválido!");
                    lblInvalido.setVisible(true);
                }else{
                    lblInvalido.setVisible(false);
                }
            }
        }
        else{
            lblInvalido.setVisible(false);
        }
    }//GEN-LAST:event_txtCnpj_clienteFocusLost

    private void txtTel1_clienteFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_txtTel1_clienteFocusLost

    }//GEN-LAST:event_txtTel1_clienteFocusLost

    private void pangClienteFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_pangClienteFocusGained
        // TODO add your handling code here:
    }//GEN-LAST:event_pangClienteFocusGained

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(FrmCadCliente.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(FrmCadCliente.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(FrmCadCliente.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(FrmCadCliente.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>
        //</editor-fold>
        //</editor-fold>
        //</editor-fold>
        /* Create and display the form */
        
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new FrmCadCliente().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton botCancelar;
    private javax.swing.JButton botEditar_cliente;
    private javax.swing.JButton botExcluir_cliente;
    private javax.swing.JButton botLimpar;
    private javax.swing.JButton botNovoPedido;
    private javax.swing.JButton botNovo_cliente;
    private javax.swing.JButton botPesquisar;
    private javax.swing.JButton botSalvar;
    private javax.swing.JButton botVerPedidos;
    private javax.swing.JRadioButton bradPessoaFisica;
    private javax.swing.JRadioButton bradPessoaJuridica;
    private javax.swing.JComboBox cmbCidade_cliente;
    private javax.persistence.EntityManager entityManager;
    private javax.swing.ButtonGroup grpbTipo_cliente;
    private javax.swing.JLabel lblBairro;
    private javax.swing.JLabel lblCEP;
    private javax.swing.JLabel lblCidade;
    private javax.swing.JLabel lblCnpj;
    private javax.swing.JLabel lblEmail;
    private javax.swing.JLabel lblEndereco;
    private javax.swing.JLabel lblFantasia;
    private javax.swing.JLabel lblIE;
    private javax.swing.JLabel lblId_cliente;
    private javax.swing.JLabel lblInvalido;
    private javax.swing.JLabel lblNome;
    private javax.swing.JLabel lblObs;
    private javax.swing.JLabel lblTelefone;
    private javax.swing.JLabel lblTelefone2;
    private javax.swing.JLabel lblTipo;
    private javax.swing.JPanel panCadastro;
    private javax.swing.JScrollPane panObs;
    private javax.swing.JPanel panPesquisa;
    private javax.swing.JScrollPane panTabela;
    private javax.swing.JTabbedPane pangCliente;
    private java.util.List<pacoteframe.TbCliente> tbClienteList;
    private java.util.List<pacoteframe.TbCliente> tbClienteList1;
    private javax.persistence.Query tbClienteQuery;
    private javax.persistence.Query tbClienteQuery1;
    private javax.swing.JTable tblCliente;
    private javax.swing.JTextField txtBairro_cliente;
    private javax.swing.JFormattedTextField txtCep_cliente;
    private javax.swing.JFormattedTextField txtCnpj_cliente;
    private javax.swing.JTextField txtEmail_cliente;
    private javax.swing.JTextField txtEndereco_cliente;
    private javax.swing.JTextField txtFantasia_cliente;
    private javax.swing.JTextField txtId_cliente;
    private javax.swing.JFormattedTextField txtIe_cliente;
    private javax.swing.JTextField txtNome_cliente;
    private javax.swing.JTextArea txtObs_cliente;
    private javax.swing.JTextField txtPesquisa_cliente;
    private javax.swing.JFormattedTextField txtTel1_cliente;
    private javax.swing.JFormattedTextField txtTel2_cliente;
    // End of variables declaration//GEN-END:variables

}